package tree;

public class ConstructBinaryTreeFromPreorderAndInorderTraversal105 {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder == null || preorder.length == 0) {
            return null;
        }
        return buildTreeRecursively(preorder, 0, preorder.length-1,
                                    inorder, 0, inorder.length-1);
    }

    public TreeNode buildTreeRecursively(int[] preorder, int preStart, int preEnd,
                                         int[] inorder, int inStart, int inEnd) {
        if (inStart > inEnd) {
            return null;
        }
        TreeNode root = new TreeNode(preorder[preStart]);
        int InRootIndex = searchInorderIndex(preorder[preStart], inorder, inStart, inEnd);
        root.left = buildTreeRecursively(preorder, preStart+1, preStart+InRootIndex-inStart,
                                        inorder, inStart, InRootIndex-1);
        root.right = buildTreeRecursively(preorder, preStart+InRootIndex-inStart+1, preEnd,
                                        inorder, InRootIndex+1, inEnd);
        return root;
    }

    public int searchInorderIndex(int target, int[] inorder, int start, int end) {
        for (int i = start; i <= end; i++) {
            if (target == inorder[i]) {
                return i;
            }
        }
        return -1;
    }
}
